package com.itheima.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.User;
import com.itheima.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;

import static com.itheima.controller.Code.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserServiceImpl userService;

	//分页查询用户
    @PostMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable int currentPage,@PathVariable int pageSize,@RequestBody User user) throws IOException {
        Page<User> userPage = new Page<>(currentPage,pageSize);
        userService.page(userPage);
        PageBean<User> pageBean = new PageBean<>(userPage.getTotal(), userPage.getRecords());

        return new Result(GET_OK,pageBean);
    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody  User user) {
        if (userService.save(user)) {
            return new Result(SAVE_OK,null,"保存成功");
        }else {
            return new Result(SAVE_ERR,null,"保存失败");
        }
    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        if (userService.removeById(id)) {
            return new Result(DELETE_OK,null,"删除成功");
        }else {
            return new Result(DELETE_ERR,null,"删除失败");
        }
    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        if (userService.updateById(user)) {
            return new Result(UPDATE_OK,null,"修改成功");
        }else {
            return new Result(UPDATE_ERR,null,"修改失败");
        }
    }

}
